#include "softmin_custom_tiling.h"
#include "kernel_operator.h"
#include "cmath"

constexpr int32_t BUFFER_NUM = 2; // tensor num for each queue

class KernelSoftMin {
public:
    __aicore__ inline KernelSoftMin() {}
    __aicore__ inline void Init(GM_ADDR x, GM_ADDR z, uint32_t totalLength, uint32_t tileNum)
    {
        elementNumPerBlk = 32 / sizeof(float);
        this->blockLength = totalLength / AscendC::GetBlockNum();
        this->tileNum = tileNum;
        this->tileLength = this->blockLength / tileNum / BUFFER_NUM;
        xGm.SetGlobalBuffer((__gm__ float *)x + this->blockLength * AscendC::GetBlockIdx(), this->blockLength);
        zGm.SetGlobalBuffer((__gm__ float *)z + this->blockLength * AscendC::GetBlockIdx(), this->blockLength);
        // 初始化缓冲区
        pipe.InitBuffer(inQueueX, BUFFER_NUM, this->tileLength * sizeof(float));
        pipe.InitBuffer(outQueueZ, BUFFER_NUM, this->tileLength * sizeof(float));
        pipe.InitBuffer(tmpBuffer1, elementNumPerBlk * sizeof(float));
        pipe.InitBuffer(tmpBuffer2, this->tileLength * sizeof(float));
        pipe.InitBuffer(tmpBuffer3, this->tileLength * sizeof(float));
        pipe.InitBuffer(expBuffer, this->tileLength * sizeof(float));
        pipe.InitBuffer(scalarBuffer, sizeof(float));
        pipe.InitBuffer(vectorBuffer, this->tileLength * sizeof(float));
        
        // 初始化全局统计量
        this->global_max = -INFINITY;
        this->global_sum = 0.0f;
    }
    __aicore__ inline void Process()
    {
        // 两阶段处理
        ComputeGlobalStats();  // 阶段1：计算全局统计量
        ComputeGlobalSoftMin(); // 阶段2：计算SoftMin结果
    }

private:
    // 阶段1：计算全局最大值和指数和
    __aicore__ inline void ComputeGlobalStats()
    {
        int32_t loopCount = this->tileNum * BUFFER_NUM;
        for (int32_t i = 0; i < loopCount; i++) {
            CopyIn(i);
            ComputeTileStats(i);  // 合并最大值和和的计算
        }
    }

    __aicore__ inline void CopyIn(int32_t progress)
    {
        AscendC::LocalTensor<float> xLocal = inQueueX.AllocTensor<float>();
        AscendC::DataCopy(xLocal, xGm[progress * this->tileLength], this->tileLength);
        inQueueX.EnQue(xLocal);
    }
    
    // 合并的统计计算函数
    __aicore__ inline void ComputeTileStats(int32_t progress)
    {
        AscendC::LocalTensor<float> xLocal = inQueueX.DeQue<float>();
        
        // 第一次遍历：找到当前tile的最大值
        AscendC::LocalTensor<float> tileMax = scalarBuffer.Get<float>();
        uint32_t shape[] = {1, (uint32_t)this->tileLength};
        AscendC::ReduceMax<float, AscendC::Pattern::Reduce::AR, true>(
            tileMax, xLocal, shape, true);
        
        float current_max = tileMax.GetValue(0);
        // 更新全局最大值
        if (current_max > this->global_max) {
            this->global_max = current_max;
        }
        
        inQueueX.FreeTensor(xLocal);
    }
    
    // 阶段2：重新计算指数和并生成最终结果
    __aicore__ inline void ComputeGlobalSoftMin()
    {
        // 重新计算全局和（使用确定的this->global_max）
        this->global_sum = 0.0f;
        
        int32_t loopCount = this->tileNum * BUFFER_NUM;
        
        // 第一遍：重新计算全局和
        for (int32_t i = 0; i < loopCount; i++) {
            CopyIn(i);
            ComputeTileSum(i);
        }
        
        // 第二遍：计算最终的SoftMin结果
        for (int32_t i = 0; i < loopCount; i++) {
            CopyIn(i);
            ComputeSoftmin(i);
            CopyOut(i);
        }
    }

    __aicore__ inline void ComputeTileSum(int32_t progress)
    {
        AscendC::LocalTensor<float> xLocal = inQueueX.DeQue<float>();
        
        AscendC::LocalTensor<float> shifted = tmpBuffer2.Get<float>();
        AscendC::LocalTensor<float> exp_vals = expBuffer.Get<float>();
        AscendC::LocalTensor<float> tile_sum = scalarBuffer.Get<float>();
        AscendC::LocalTensor<float> max_broadcast = vectorBuffer.Get<float>();
        
        // 广播全局最大值
        AscendC::Duplicate(max_broadcast, this->global_max, this->tileLength);
        
        // 计算 x - this->global_max (数值稳定性)
        AscendC::Sub(shifted, xLocal, max_broadcast, this->tileLength);
        
        // 计算 -shifted = -(x - this->global_max) = this->global_max - x
        AscendC::Muls(shifted, shifted, -1.0f, this->tileLength);
        
        // 计算 exp(this->global_max - x)
        AscendC::Exp(exp_vals, shifted, this->tileLength);
        
        // 累加到全局和
        AscendC::LocalTensor<float> workspace_sum = tmpBuffer3.Get<float>(); 
        AscendC::ReduceSum<float>(tile_sum, exp_vals, workspace_sum, this->tileLength);
        this->global_sum += tile_sum.GetValue(0);
        
        inQueueX.FreeTensor(xLocal);
    }

    __aicore__ inline void ComputeSoftmin(int32_t progress)
    {
        AscendC::LocalTensor<float> xLocal = inQueueX.DeQue<float>();
        AscendC::LocalTensor<float> zLocal = outQueueZ.AllocTensor<float>();
        AscendC::LocalTensor<float> shifted = tmpBuffer2.Get<float>();
        AscendC::LocalTensor<float> exp_vals = expBuffer.Get<float>();
        AscendC::LocalTensor<float> max_broadcast = vectorBuffer.Get<float>();
        AscendC::LocalTensor<float> sum_broadcast = vectorBuffer.Get<float>(); // 复用vectorBuffer
            
        // 广播全局最大值
        AscendC::Duplicate(max_broadcast, this->global_max, this->tileLength);
            
        // 计算数值稳定的SoftMin
        // shifted = x - this->global_max
        AscendC::Sub(shifted, xLocal, max_broadcast, this->tileLength);
        // shifted = -(x - this->global_max) = this->global_max - x  
        AscendC::Muls(shifted, shifted, -1.0f, this->tileLength);
        // exp_vals = exp(this->global_max - x)
        AscendC::Exp(exp_vals, shifted, this->tileLength);
        
        // 广播全局和
        AscendC::Duplicate(sum_broadcast, this->global_sum, this->tileLength);
        // zLocal = exp(this->global_max - x) / this->global_sum
        AscendC::Div(zLocal, exp_vals, sum_broadcast, this->tileLength);
        
        outQueueZ.EnQue(zLocal);
        inQueueX.FreeTensor(xLocal);
    }

    __aicore__ inline void CopyOut(int32_t progress)
    {
        AscendC::LocalTensor<float> zLocal = outQueueZ.DeQue<float>();
        AscendC::DataCopy(zGm[progress * this->tileLength], zLocal, this->tileLength);
        outQueueZ.FreeTensor(zLocal);
    }

private:
    AscendC::TPipe pipe;
    AscendC::TQue<AscendC::TPosition::VECIN, BUFFER_NUM> inQueueX;
    AscendC::TQue<AscendC::TPosition::VECOUT, BUFFER_NUM> outQueueZ;
    AscendC::TBuf<AscendC::QuePosition::VECCALC> tmpBuffer1;
    AscendC::TBuf<AscendC::QuePosition::VECCALC> tmpBuffer2;
    AscendC::TBuf<AscendC::QuePosition::VECCALC> tmpBuffer3;
    AscendC::TBuf<AscendC::QuePosition::VECCALC> expBuffer;
    AscendC::TBuf<AscendC::QuePosition::VECCALC> scalarBuffer;
    AscendC::TBuf<AscendC::QuePosition::VECCALC> vectorBuffer;
    AscendC::GlobalTensor<float> xGm;
    AscendC::GlobalTensor<float> zGm;
    uint32_t blockLength;
    uint32_t tileNum;
    uint32_t tileLength;
    uint32_t elementNumPerBlk = 0;
    // 全局统计量
    float global_max;
    float global_sum;
};

extern "C" __global__ __aicore__ void softmin_custom(GM_ADDR x, GM_ADDR z, SoftMinCustomTilingData tiling)
{
    KernelSoftMin op;
    op.Init(x, z, tiling.totalLength, tiling.tileNum);
    op.Process();
}
